package com.zusmart.core.interceptor;

import com.zusmart.base.util.Assert;
import com.zusmart.core.bean.BeanDefinition;
import com.zusmart.core.bean.cause.BeanInstanceNotFoundException;
import com.zusmart.core.proxy.ProxyFactory;
import com.zusmart.core.proxy.ProxyHandler;

public class InterceptorHandler implements ProxyHandler {

	private final BeanDefinition beanDefinition;

	public InterceptorHandler(BeanDefinition beanDefinition) {
		Assert.isNull(beanDefinition, "bean definition must not be null");
		this.beanDefinition = beanDefinition;
	}

	@Override
	public ProxyFactory getFactory() {
		Object beanInstance = null;
		try {
			beanInstance = this.beanDefinition.getBeanInstance();
		} catch (BeanInstanceNotFoundException e) {
			throw new IllegalStateException(String.format("get bean instance failed (%s)", this.beanDefinition.toString()));
		}
		if (null == beanInstance) {
			throw new IllegalStateException(String.format("get bean instance failed (%s)", this.beanDefinition.toString()));
		}
		if (beanInstance instanceof ProxyFactory) {
			return (ProxyFactory) beanInstance;
		}
		throw new IllegalStateException(String.format("%s must implement ProxyFactory", this.beanDefinition.toString()));
	}

}